package com.tju.resource.oauth.controller.tb;

import com.tju.resource.model.TbClient;
import com.tju.resource.server.TbClientService;
import com.tju.resource.tool.result.Result;
import com.tju.resource.tool.result.ResultEnum;
import com.tju.resource.tool.result.ResultUtil;
import com.tju.resource.tool.tool.ClientParameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Objects;

@RestController
public class TbClientController {
    private final String prefix = "client";

    @Autowired
    private TbClientService tbClientService;

    /**
     * 查询
     *
     * @param parameters
     * @return
     */
    @PreAuthorize("hasAuthority('sys:spClient:client:list')")
    @PostMapping(prefix + "/getClientAll")
    public Result<Object> getClientAll(@RequestBody ClientParameters parameters) {
        return tbClientService.getClientAll(parameters);
    }

    /**
     * 添加
     *
     * @param tbClient
     * @return
     */
    @PreAuthorize("hasAuthority('sys:spClient:client:add')")
    @PostMapping(prefix + "/addClientAll")
    public Result<Object> addClientAll(@Valid @RequestBody TbClient tbClient, BindingResult result) {
        if (result.hasErrors()) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
        } else
            return tbClientService.addClientAll(tbClient);
    }

    /**
     * 删除
     *
     * @param tbClient
     * @return
     */
    @PreAuthorize("hasAuthority('sys:spClient:client:delete')")
    @PostMapping(prefix + "/delClientAll")
    public Result<Object> delClientAll(@RequestBody TbClient tbClient) {
        return tbClientService.delClientAll(tbClient);
    }

    /**
     * 修改
     *
     * @param tbClient
     * @return
     */
    @PreAuthorize("hasAuthority('sys:spClient:client:edit')")
    @PostMapping(prefix + "/updClientAll")
    public Result<Object> updClientAll(@Valid @RequestBody TbClient tbClient, BindingResult result) {
        if (result.hasErrors()) {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
        } else
            return tbClientService.updClientAll(tbClient);
    }
}
